﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarModule : MonoBehaviour {
    Animator anim;
    float speed = 0f;

    SpeedCounter sc;

    private void Start()
    {
        anim = GetComponent<Animator>();
        sc = new SpeedCounter(10);
    }

    //拖拽
    private void OnMouseDrag()
    {
        
    }

    //按下
    private void OnMouseDown()
    {
        //点击
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_Car_Click);
    }

    //抬起
    private void OnMouseUp()
    {
        
    }

    private void Update()
    {
        if (anim == null) return;

        if (sc.Isfull())
        {
            //计算速度
            speed = sc.GetSpeed();
            anim.SetFloat("speed", speed);
        }
        else
        {
            //填充   
            sc.Insert(transform.position, Time.deltaTime);
        }
        
    }

    class SpeedCounter
    {
        int length = 10;
        //int count = 0;
        Queue<Vector3> waypoints;//10帧的路径点
        Queue<float> timepeers;//10帧的时间片

        public SpeedCounter(int frame)
        {
            waypoints = new Queue<Vector3>();
            timepeers = new Queue<float>();
            length = frame;
        }

        public bool Isfull()
        {
            if (waypoints.Count != timepeers.Count)
            {
                waypoints.Clear();
                timepeers.Clear();
                return false;
            }
            if (waypoints.Count == length)
                return true;
            else
            {
                if (waypoints.Count < length)
                    return false;

                if (waypoints.Count > length)
                {
                    while (waypoints.Count != length)
                    {
                        waypoints.Dequeue();
                        timepeers.Dequeue();
                    }
                    return true;
                }
                return false;
            }
        }

        public void Insert(Vector3 p,float t)
        {
            waypoints.Enqueue(p);
            timepeers.Enqueue(t);
        }

        public float GetSpeed()
        {
            int sum = waypoints.Count;
            float time = 0;
            float dis = 0;
            Vector3 start = waypoints.Dequeue();
            //float starttime = timepeers.Dequeue();

            foreach (var v in waypoints)
            {
                dis += Vector3.Distance(start, v);
                start = v;
            }

            timepeers.Dequeue();
            foreach (var v in timepeers)
            {
                time += v;
            }

            return dis / time;

        }

        public float Speed()
        {
            return 0;
        }
    }
}

